
package com.afd.ozblip.activity;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.ParseJson;
import com.afd.ozblip.util.StringUtil;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.TextView;

public class UploadPhotoActivity extends BaseActivity {

    // TODO 变量区域
    /****************** 视图变量 **************************/
    private LinearLayout commonRight;
    private ImageView uploadImageIv;
    private TextView dishNameTv;
    private RatingBar dishStarRb;
    private EditText dishPriceEt;
    private EditText photoTitleEt;
    private RadioGroup typeRg;
    // private RadioButton dishRb;
    // private RadioButton envRb;
    // private RadioButton otherRb;
    private LinearLayout dishLayout;
    private LinearLayout otherLayout;
    private LinearLayout typeLayout;
    /****************** 数据变量 **************************/
    private String businessId;
    private String parentClassName;
    private String childClassName;
    private String fileBase64;
    private String dishId;
    private float dishStar;
    private String dishPrice;
    private Bitmap headBitmap;
    private String imageType = "1";
    private String photoTitle;
    private boolean isChooseImage = false;
    private Map<String, Object> resultMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.upload_dish_photo);
        // 启动返回功能
        toBack();
        // 寻找视图
        findViews();
        // 设置监听
        setListeners();
        // 获取参数
        getBundle();
    }

    /**
     * 寻找视图
     */
    public void findViews() {
        this.commonRight = (LinearLayout) findViewById(R.id.ll_common_right);
        this.uploadImageIv = (ImageView) findViewById(R.id.iv_business_recommend_image);
        this.dishNameTv = (TextView) findViewById(R.id.tv_business_recommend_dishName);
        this.dishStarRb = (RatingBar) findViewById(R.id.rb_business_recommend_dishStar);
        this.dishPriceEt = (EditText) findViewById(R.id.et_business_recommend_dishPrice);
        this.photoTitleEt = (EditText) findViewById(R.id.et_business_recommend_photoTitle);
        this.typeRg = (RadioGroup) findViewById(R.id.rg_upload_type);
        // this.dishRb = (RadioButton) findViewById(R.id.rb_upload_type_dish);
        // this.envRb = (RadioButton) findViewById(R.id.rb_upload_type_env);
        // this.otherRb = (RadioButton) findViewById(R.id.rb_upload_type_other);
        this.dishLayout = (LinearLayout) findViewById(R.id.ll_upload_dish_layout);
        this.otherLayout = (LinearLayout) findViewById(R.id.ll_upload_ohter_layout);
        this.typeLayout = (LinearLayout) findViewById(R.id.upload_photo_type_ll);
    }

    /**
     * 设置监听
     */
    public void setListeners() {
        View.OnClickListener uploadClick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_common_right:
                        if ("1".equals(imageType)) {
                            dishStar = dishStarRb.getRating();
                            dishPrice = dishPriceEt.getText().toString();
                            if (verifyDishData()) {
                                requestUploadPhotoData();
                            }
                        } else {
                            photoTitle = photoTitleEt.getText().toString();
                            if (verifyOtherData()) {
                                requestUploadOtherPhotoData();
                            }
                        }
                        break;
                    case R.id.iv_business_recommend_image:
                        showImageMenuDialog();
                        break;
                    case R.id.tv_business_recommend_dishName:
                        Intent choiceDishIntent = new Intent(
                                UploadPhotoActivity.this, ChoiceDishActivity.class);
                        choiceDishIntent.putExtra("businessId", businessId);
                        startActivityForResult(choiceDishIntent, 3);
                        break;
                    default:
                        break;
                }
            }
        };
        this.commonRight.setOnClickListener(uploadClick);
        this.uploadImageIv.setOnClickListener(uploadClick);
        this.dishNameTv.setOnClickListener(uploadClick);
        this.typeRg
                .setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        if (checkedId == R.id.rb_upload_type_dish) {
                            imageType = "1";
                            dishLayout.setVisibility(0);
                            otherLayout.setVisibility(8);
                        } else if (checkedId == R.id.rb_upload_type_env) {
                            imageType = "2";
                            otherLayout.setVisibility(0);
                            dishLayout.setVisibility(8);
                        } else {
                            imageType = "3";
                            otherLayout.setVisibility(0);
                            dishLayout.setVisibility(8);
                        }
                    }
                });
    }

    /**
     * 获取传递的参数
     */
    private void getBundle() {
        Intent intent = getIntent();
        businessId = intent.getStringExtra("businessId");
        this.parentClassName = intent.getStringExtra("parentClassName");
        this.childClassName = intent.getStringExtra("childClassName");
        if ("美食".equals(parentClassName) || "快餐".equals(childClassName)) {
            typeLayout.setVisibility(0);
            dishLayout.setVisibility(0);
            otherLayout.setVisibility(8);
        } else {
            imageType = "3";
            typeLayout.setVisibility(8);
            dishLayout.setVisibility(8);
            otherLayout.setVisibility(0);
        }
    }

    /**
     * 验证菜图数据
     */
    private boolean verifyDishData() {
        if (!isChooseImage) {
            showLongToast(this, "请选择图片！", true);
            return false;
        }
        if (StringUtil.isNullOrEmpty(dishId)) {
            showLongToast(this, "请选择菜名！", true);
            return false;
        }
        if (dishStar == 0) {
            showLongToast(this, "请选择评价分数！", true);
            return false;
        }
        if (StringUtil.isNullOrEmpty(dishPrice)) {
            showLongToast(this, "请输入价格！", true);
            return false;
        }

        return true;
    }

    /**
     * 验证其它数据
     */
    private boolean verifyOtherData() {
        if (!isChooseImage) {
            showLongToast(this, "请选择图片！", true);
            return false;
        }
        if (StringUtil.isNullOrEmpty(photoTitle)) {
            showLongToast(this, "请输入标题！", true);
            return false;
        }

        return true;
    }

    // TODO 提交上传图片数据
    /**
     * 获取上传图片数据
     */
    private void requestUploadPhotoData() {
        if (StringUtil.isNullOrEmpty(businessId)) {
            return;
        }
        if (commonUserInfo == null) {
            return;
        }
        AsyncLoadData ald = new AsyncLoadData(this, "加载中...",
                new AsyncAction() {

                    @Override
                    public void doLoad() throws Exception {
                        // 获取提交参数
                        Map<String, Object> addDishParamMap = new HashMap<String, Object>();
                        addDishParamMap.put("sellerId", businessId);
                        addDishParamMap.put("userId",
                                commonUserInfo.getUserId());
                        addDishParamMap.put("uploadImg", fileBase64);
                        addDishParamMap.put("imgType", imageType);
                        addDishParamMap.put("dishId", dishId);
                        addDishParamMap.put("sellerStar", dishStar);
                        addDishParamMap.put("prices", dishPrice);
                        // 发送请求
                        byte[] bRecommend = HttpUtil.requestByPost(
                                UploadPhotoActivity.this,
                                Constants.ADD_DISH_API, addDishParamMap);
                        if (bRecommend != null) {
                            resultMap = new ParseJson()
                                    .parseAddResultJson(bRecommend);
                        }
                    }

                    @Override
                    public void loadEnd() throws Exception {
                        boolean returnFlg = (Boolean) resultMap
                                .get("returnFlg");
                        if (returnFlg) {
                            showShortToast(UploadPhotoActivity.this, "推荐成功",
                                    true);
                            finish();
                        } else {
                            showShortToast(UploadPhotoActivity.this, "推荐失败",
                                    true);
                        }
                    }

                });
        ald.execute(0);

    }

    // TODO 提交上传图片数据
    /**
     * 获取上传图片数据
     */
    private void requestUploadOtherPhotoData() {
        if (StringUtil.isNullOrEmpty(businessId)) {
            return;
        }
        if (commonUserInfo == null) {
            return;
        }
        AsyncLoadData ald = new AsyncLoadData(this, "加载中...",
                new AsyncAction() {

                    @Override
                    public void doLoad() throws Exception {
                        // 获取提交参数
                        Map<String, Object> addDishParamMap = new HashMap<String, Object>();
                        addDishParamMap.put("sellerId", businessId);
                        addDishParamMap.put("userId",
                                commonUserInfo.getUserId());
                        addDishParamMap.put("uploadImg", fileBase64);
                        addDishParamMap.put("imgType", imageType);
                        addDishParamMap.put("imgTitle", photoTitle);
                        // 发送请求
                        byte[] bRecommend = HttpUtil.requestByPost(
                                UploadPhotoActivity.this,
                                Constants.ADD_DISH_API, addDishParamMap);
                        if (bRecommend != null) {
                            resultMap = new ParseJson()
                                    .parseAddResultJson(bRecommend);
                        }
                    }

                    @Override
                    public void loadEnd() throws Exception {
                        boolean returnFlg = (Boolean) resultMap
                                .get("returnFlg");
                        if (returnFlg) {
                            showShortToast(UploadPhotoActivity.this, "推荐成功",
                                    true);
                            finish();
                        } else {
                            showShortToast(UploadPhotoActivity.this, "推荐失败",
                                    true);
                        }
                    }

                });
        ald.execute(0);

    }

    public static final int PHOTOHRAPH = 1;// 拍照
    public static final int PHOTOZOOM = 2; // 缩放
    public static final int PHOTORESOULT = 3;// 结果

    public static final String IMAGE_UNSPECIFIED = "image/*";

    private byte[] mContent;

    private void showImageMenuDialog() {
        final String[] arrayFruit = new String[] {
                "相机拍摄", "手机相册"
        };

        final Dialog alertDialog = new AlertDialog.Builder(
                UploadPhotoActivity.this).setTitle("图片来源")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setItems(arrayFruit, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // switch (which) {
                        // case 0:
                        // Intent cameraI = new Intent(
                        // MediaStore.ACTION_IMAGE_CAPTURE);
                        // cameraI.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                        // .fromFile(new File(Environment
                        // .getExternalStorageDirectory(),
                        // "temp.jpg")));
                        // startActivityForResult(cameraI, PHOTOHRAPH);
                        // break;
                        // case 1:
                        // Intent pictureI = new Intent(Intent.ACTION_PICK,
                        // null);
                        // pictureI.setDataAndType(
                        // MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        // IMAGE_UNSPECIFIED);
                        // startActivityForResult(pictureI, PHOTOZOOM);
                        // break;
                        //
                        // default:
                        // break;
                        // }
                        if (which == 0) {
                            Intent getImageByCamera = new Intent(
                                    "android.media.action.IMAGE_CAPTURE");
                            startActivityForResult(getImageByCamera, 1);
                        } else {
                            Intent getImage = new Intent(
                                    Intent.ACTION_GET_CONTENT);
                            getImage.addCategory(Intent.CATEGORY_OPENABLE);
                            getImage.setType("image/jpeg");
                            startActivityForResult(getImage, 0);
                        }
                    }
                }).create();
        alertDialog.show();
    }

    // 剪切图片
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "circle");
        // aspectX aspectY 是宽高的比例
        // intent.putExtra("aspectX", 1);
        // intent.putExtra("aspectY", 1);
        // // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTORESOULT);
    }

    protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        // if (requestCode == PHOTOHRAPH) {
        // // 设置文件保存路径这里放在跟目录下
        // File picture = new File(Environment.getExternalStorageDirectory()
        // + "/temp.jpg");
        // startPhotoZoom(Uri.fromFile(picture));
        // }
        // if (intent == null) {
        // return;
        // }
        // // 相册
        // // 读取相册缩放图片
        // if (requestCode == PHOTOZOOM) {
        // startPhotoZoom(intent.getData());
        // }
        //
        // // 处理结果
        // if (requestCode == PHOTORESOULT) {
        // Bundle extras = intent.getExtras();
        // if (extras != null) {
        // headBitmap = extras.getParcelable("data");
        // this.ideaImageIv.setImageBitmap(headBitmap);
        // ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        // headBitmap.compress(CompressFormat.JPEG, 100, bStream);
        //
        // byte[] bytes = bStream.toByteArray();
        // fileBase64 = Base64.encodeToString(bytes, Base64.DEFAULT);
        // // 设置创意类型
        // ideaType = TYPE_IMAGE;
        // // uploadFile();
        // }
        // }
        switch (requestCode) {
            case 0:
                try {
                    ContentResolver resolver = getContentResolver();
                    // 获得图片的uri
                    Uri originalUri = intent.getData();
                    // 将图片内容解析成字节数组
                    mContent = readStream(resolver.openInputStream(Uri
                            .parse(originalUri.toString())));
                    if (mContent == null) {
                        return;
                    }
                    // 将字节数组转换为ImageView可调用的Bitmap对象
                    headBitmap = getPicFromBytes(mContent, null);
                    // //把得到的图片绑定在控件上显示
                    // this.ideaImageIv.setImageBitmap(headBitmap);
                    // BitmapDrawable bd = new BitmapDrawable(getResources(),
                    // headBitmap);
                    uploadImageIv.setImageBitmap(headBitmap);
                    // imgDeleteIv.setVisibility(0);
                    fileBase64 = Base64.encodeToString(mContent, Base64.DEFAULT);
                    // 设置选择了图片
                    isChooseImage = true;
                } catch (Exception e) {
                    // System.out.println(e.getMessage());
                }
                break;
            case 1:
                try {
                    super.onActivityResult(requestCode, resultCode, intent);
                    if (intent == null) {
                        return;
                    }
                    Bundle extras = intent.getExtras();
                    headBitmap = (Bitmap) extras.get("data");
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    headBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    mContent = baos.toByteArray();
                    fileBase64 = Base64.encodeToString(mContent, Base64.DEFAULT);
                    uploadImageIv.setImageBitmap(headBitmap);
                    // 设置选择了图片
                    isChooseImage = true;
                    // imgDeleteIv.setVisibility(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case 3:
                if (intent != null) {
                    Bundle extras = intent.getExtras();
                    dishId = extras.getString("dishId");
                    dishNameTv.setText(extras.getString("dishName"));
                }
                break;

            default:
                break;
        }
    }

    public static Bitmap getPicFromBytes(byte[] bytes,
            BitmapFactory.Options opts) {
        if (bytes != null)
            if (opts != null)
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
                        opts);
            else
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return null;
    }

    public static byte[] readStream(InputStream inStream) throws Exception {
        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;

    }
}
